package cn.itcast.bos.before.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.activemq.tool.WebServer;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.before.utils.MailUtils;
import cn.itcast.crm.domain.Customer;

@ParentPackage("json-default")
@Controller
@Namespace("/")
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer>{
	private String code;
	private String activeCode;
	public void setActiveCode(String activeCode) {
		this.activeCode = activeCode;
	}

	public void setCode(String code) {
		this.code = code;
	}
	@Autowired
	private RedisTemplate<String, String> redistemplate;
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	@Action(value="getcheckcode")
	public String getcheckcode() throws Exception{
		final String string = RandomStringUtils.randomNumeric(4);
		System.out.println(string);
		ServletActionContext.getRequest().getSession().setAttribute(t.getTelephone(), string);
//		AliyunSmsUtils.sendSms(t.getTelephone(),string);
		Map<String,String> map=new HashMap<String,String>();
		map.put("telephone", t.getTelephone());
		map.put("code", string);
		send("sendmsg", map);
		return NONE;
	}
	
	@Action(value="regist",results={@Result(name="success",type="redirect",location="/signup-success.html"),
			@Result(name="input",location="/signup.html",type="redirect")})
	public String regist(){
		String str = (String) ServletActionContext.getRequest().getSession().getAttribute(t.getTelephone());
		if(code==null||!code.equals(str)){
			return INPUT;
		}else{
			System.out.println(t);
			WebClient.create("http://localhost:8082/crm_management/service/crm/customerservice/customer").
			type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).post(t);
			//获得随机激活码,一式两份，一份存在redis里面，一份邮箱发给客户
			activeCode = RandomStringUtils.randomNumeric(32);
			//将激活码存入redis
			redistemplate.opsForValue().set(t.getTelephone(), activeCode, 24, TimeUnit.HOURS);
			String content="您好，点击以下链接验证您的邮箱："+
			"<a href='localhost:8083"+MailUtils.mailUrl()+"/checkemail?telephone="+t.getTelephone()+"&activeCode="+activeCode+"'>邮箱绑定</a>";
			System.out.println(content);
			System.out.println(redistemplate.opsForValue().get(t.getTelephone()));
//			MailUtils.sendMail("邮箱验证",content,t.getEmail());
			Map<String,String> map=new HashMap<String,String>();
			map.put("title", "邮箱验证");
			map.put("content", content);
			map.put("email",  t.getEmail());
			send("sendEmail", map);
			return SUCCESS;
		}
		
	}
	
	@Action(value="login",results={@Result(name="success",
			type="redirect",location="/#/myhome"),
			@Result(name="login",type="redirect",location="/login.html")})
	public String login(){
		Customer customer = WebClient.create("http://localhost:8082/crm_management/service/"
				+ "crm/customerservice/customer/TelephoneAndPassword").
				query("telephone", t.getTelephone()).
				query("password", t.getPassword()).accept(MediaType.APPLICATION_JSON).
				get(Customer.class);
		System.out.println(customer);
		if(customer==null){
			return LOGIN;
		}else{
			ServletActionContext.getRequest().getSession().
			setAttribute("customer", customer);
			System.out.println("-----------------------------------------------------");
			return SUCCESS;
		}
	}
	
	@Action(value="checkemail")
	public String checkemail() throws Exception{
		//获取custoemer
		ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
		String inredis=redistemplate.opsForValue().get(t.getTelephone());
		System.out.println(t.getTelephone()+"-"+activeCode+"  "+inredis);
		Customer customer = WebClient.create("http://localhost:8082/crm_management/service/crm/customerservice/customer/"+t.getTelephone()).
				type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).get(Customer.class);
		if(activeCode==null||inredis==null||!activeCode.equals(inredis)){
			ServletActionContext.getResponse().getWriter().write("绑定失败");
			return NONE;
		}else{
			//未绑定
			if(customer.getType()==null){
				//更新customer,绑定邮箱
				redistemplate.delete(t.getTelephone());
				WebClient.create("http://localhost:8082/crm_management/service/crm/customerservice/customer/"+t.getTelephone()).
				type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).put(null);
				System.out.println(redistemplate.opsForValue().get(t.getTelephone()));
				//已经绑定
			}else{
				ServletActionContext.getResponse().getWriter().write("已经绑定");
				return NONE;
			}
		}
		ServletActionContext.getResponse().getWriter().write("绑定成功");
		return NONE;
	}
	
	public  void send(String queueName,final Map<String,String> map){
		jmsTemplate.send(queueName,new MessageCreator(){
			@Override
			public Message createMessage(Session session) throws JMSException {
				// TODO Auto-generated method stub
				MapMessage message = session.createMapMessage();
				Set<String> keySet = map.keySet();
				for (String key : keySet) {
					message.setString(key, map.get(key));
				}
				return message;
			}});
	}
}
